package com.face.facerecognition.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.face.facerecognition.entity.AuthTokenStatus;
import com.face.facerecognition.mapper.AuthTokenStatusMapper;
import com.face.facerecognition.service.AuthTokenStatusService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author rui
 * @since 2025-01-10
 */
@Service
public class AuthTokenStatusServiceImpl extends ServiceImpl<AuthTokenStatusMapper, AuthTokenStatus> implements AuthTokenStatusService {
    public List<AuthTokenStatus> queryList() {
        return lambdaQuery().list();
    }

    /**
     * //        {
     * //    "success": false,
     * //    "result": null,
     * //    "code": 283450,
     * //    "message": "认证尚未开始。Verification is not started yet.",
     * //    "log_id": "1877630606465113529"
     * //}
     *
     * @param token
     * @param jsonObject
     */
    @Override
    public boolean updateStatusByToken(String token, JSONObject jsonObject) {
        AuthTokenStatus authTokenStatus = new AuthTokenStatus();
        if (jsonObject.getBoolean("success")) {
            authTokenStatus.setRealNameVerified(1);
            authTokenStatus.setMessage("实名认证成功");
        } else {
            authTokenStatus.setRealNameVerified(0);
            authTokenStatus.setMessage(jsonObject.getString("message"));
        }
        authTokenStatus.setVerificationTime(new Date());
        //已认证的状态不再更新
        boolean update = lambdaUpdate()
                .eq(AuthTokenStatus::getToken, token)
                .and(wrapper -> wrapper.isNull(AuthTokenStatus::getRealNameVerified)
                        .or()
                        .ne(AuthTokenStatus::getRealNameVerified, 1)
                )
                .update(authTokenStatus);
        return authTokenStatus.getRealNameVerified()==1 && update;
    }

    @Override
    public AuthTokenStatus isAuth(String token) {
        return lambdaQuery()
                .eq(AuthTokenStatus::getToken, token)
                .one();
    }

    @Override
    public AuthTokenStatus isAuthRealName(String token) {
        return lambdaQuery()
                .eq(AuthTokenStatus::getToken, token)
                .eq(AuthTokenStatus::getRealNameVerified, 1)
                .one();
    }
}
